package com.geostar.gmp.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.geostar.gmp.exception.ElementException;


/**
 * 文件名:ReadXMLUtils.java
 * 功能: 读取xml文件节点工具类
 * 目前支持方法
 * --------------------------------------
 * 初始版本 
 * 作者: yesong
 * 时间: Apr 1, 2014
 */
public class ReadXMLUtils {

//	private static final String FILE_PATH = "/mibconfig.xml";
	private static Logger LOGGER = LoggerFactory.getLogger(ReadXMLUtils.class);
	
	/** 接受xml数据的Document **/
	private static Document doc;
	
	/** InputStream对象 **/
	private static InputStream in;
	
	/**
	 * 目的: 读取节点值
	 * @param element 需要获取结果的节点名称
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static List<Element> readElementsByNode(String nodeName) throws ElementException { 
		Element root = doc.getRootElement();
		List<Element> eList = root.selectNodes(nodeName);
		
		Attribute attr = root.attribute("1.3.6.1.2.1.1.1.0");
		
		return eList;
	}
	
	/**
	 * 目的: 获取指定ID的节点
	 * @param id 指定ID，在xml文件里的ID字母必须大写，不然无法识别
	 * @return 
	 *
	 */
	public static Element readElementsById(String id) {
		Element root = doc.getRootElement();
		Element element = root.elementByID(id);
		return element;
	}
	
	public static void loadXML(String path_file){
		//获取读取方式
		SAXReader sr = new SAXReader();
		in = ReadXMLUtils.class.getResourceAsStream(path_file);
		try {
			//读取xml文件，并将读取的数据保存到docment中
			doc = sr.read(in);
		} catch (DocumentException e) {
			e.printStackTrace();
			LOGGER.error("加载xml文件出错,来自ReadXMLUtils.loadXML()方法");
		}
	}
	
	public static void closeInputStream(){
		if(in != null){
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		String path_file = "src/mibconfig.xml";
		loadXML(path_file);
		try {
			List<Element> eList = readElementsByNode("base/op/oid");
			for (Element element : eList) {
//				System.out.println(element.getTextTrim());
			}
		} catch (ElementException e) {
			e.printStackTrace();
		}
		
	}
}
